define(function (require) {


    var INNER = 1;  //内部url 本应用内请求URL
    var OUTER = 2;  //外部url 其他应用的请求URL


    var juicer = require('juicer');

    require('../lodash/index');
    require('../dialog/index');

    var CRM = {

        API : {
            //去订单分页数量总数
            'queryOrderCount' : getOuterUrl('/trade/crm/order/queryOrderCount'),
            'queryOrderList' : getOuterUrl('/trade/crm/order/queryOrderList'),
            'queryOrderListCount' : getOuterUrl('/trade/crm/order/queryOrderListCount'),
            //店铺信息
            'queryShopById' : getOuterUrl('/shop/shop/queryShopById'),
            //订单详情
            'queryOrder' : getOuterUrl('/trade/crm/order/queryOrder'),
            'getUserByShopAndMobile' : getOuterUrl('/member/getUserByShopAndMobile.do'),
            'queryShopByName' : getOuterUrl('/shop/shop/queryShopByName'),
            'queryShopByXiaoerId' : getOuterUrl('/shop/shop/queryShopByXiaoerId'),
            //催单
            'remindMarkOrder' : getOuterUrl('/trade/crm/order/remindMarkOrder'),
            //获取预售时间
            'iteminfo' : getOuterUrl('/market/api/presell/crm/iteminfo.jsonp'),
            //修改预售时间
            'updatePreSaleSendTime' : getOuterUrl('/trade/crm/order/updatePreSaleSendTime'),
            //取消订单
            'cancelOrder' : getOuterUrl('/trade/crm/order/cancelOrder'),
            //红包发送
            'sendHongbao' : '../../crm/market/sendHongbao',
            //获得地标信息
            'landmarkInfo' : getOuterUrl('/dataapi/landmark/info.do?'),
            //短信发送
            'smsSend' : getOuterUrl('/msgcenter/msg/sms/send'),
            //push推送
            'push' : getOuterUrl('/msgcenter/msg/app/push'),
            //当日订单信息统计
            'queryCurrent' : getOuterUrl('/trade/crm/order/queryCurrent'),
            //查询店铺开放城市
            'queryOpenCity' : getOuterUrl('/shop/city/queryOpenCity'),
            //登出操作
            'logOut' : getOuterUrl('/member/logout.do')
        },

        /**
         * 显示温馨提示
         * @param html
         */
        showDialog: function (html) {
            var dialog = CRM.dialog({
                title: '温馨提示：',
                quickClose: true,
                id: "crm_dialog",
                width: 330,
                zIndex: 1112,
                fixed: true,
                content: html
            });
            dialog.showModal();
        },
        /**
         * 确认操作
         * @param html
         * @param callBack
         */
        showConfirm: function (html, callBack) {
            var dialog = CRM.dialog({
                title: '温馨提示：',
                quickClose: true,
                id: "crm_dialog",
                width: 330,
                zIndex: 1112,
                fixed: true,
                okValue: "确 定",
                cancelValue: "取 消",
                cancel: function () {
                    this.close();
                },
                ok: callBack,
                content: html
            });
            dialog.showModal();
        },

        /**
         * 显示弹出层
         * @param html
         * @param node
         */
        showModal: function (html, node) {
            if (this.modalTime) {
                var diff = +new Date() - this.modalTime;
                if (this.modalTime && diff < 400) return;
            }
            var tmpNode = $(html);
            node.append(tmpNode);
            if (tmpNode.length > 1) {
                $(tmpNode[2]).modal('show');
            } else {
                $(tmpNode).modal('show');
            }
            tmpNode.off('shown.bs.modal').on('shown.bs.modal', function (e) {
                $(document).off('focusin.modal');//解决编辑器弹出层文本框不能输入的问题;
            });
            tmpNode.on('hidden.bs.modal', function (e) {
                tmpNode.remove();
            });
            tmpNode.off('shown.bs.modal').on('shown.bs.modal', function (e) {
                $(document).off('focusin.modal');//解决编辑器弹出层文本框不能输入的问题;
            });
            this.modalTime = +new Date();
        },

        goLogin : function() {
            var self = this;
            self.request({
                "type": 'POST',
                "url": self.API.logOut,
                "dataType": "json",
                "data": JSON.stringify({
                    "role": "crm"
                }),
                "success" : function(req) {
                    console.log(req)
                    var targetUrl = location.href;
                    location.href = self.getOuterUrl('/member/login.html?redirectUrl='+encodeURIComponent(targetUrl));
                }
            });
        },

        request : function(data) {
            var self = this;
            var param = {
                contentType: "application/json",
                xhrFields: {
                    withCredentials: true
                }
            };
            param = $.extend(param,data);
            param.success = function(req){
                if(req.responseCode == 10212 && req.status == false){
                    self.goLogin();
                } else {
                  data.success && data.success(req);
                }
            };
            param.error = function(e){
                if(data.error) {
                    data.error(e)
                }else {
                    self.showDialog('请求服务异常!');
                }
            };
            $.ajax(param);
        },

        /*
         * 获取url中的参数
         * @param
         *      name:{String}   参数名称
         *      [url]:{String}  url，选填
         */
        getUrlParam: function(name, url){

            var href = url || window.location.href,
                hrefName = encodeURIComponent(name)+"=",
                hrefStart = href.indexOf(hrefName),
                hrefValue = null;

            if(hrefStart > -1){

                var hrefEnd = href.indexOf("&",hrefStart);
                if(hrefEnd == -1){
                    hrefEnd = href.length;
                }
                hrefValue = decodeURIComponent(href.substring(hrefStart + hrefName.length, hrefEnd));
            }

            return hrefValue;
        },

        /**
         * 判断登陆状态，如果没登陆，需要登陆
         */
        checkLogin : function() {
            //goLogin
        },

        /**
         * 获取外部URL
         */
        getOuterUrl : getOuterUrl,

        checkEmail : function(email){
            if(!email){
                return true;
            }
            if ((email.length > 128) || (email.length < 6)) {
                return false;
            }
            var format = /^[A-Za-z0-9+]+[A-Za-z0-9\.\_\-+]*@([A-Za-z0-9\-]+\.)+[A-Za-z0-9]+$/;
            if (!email.match(format)) {
                return false;
            }
            return true;
        },
        /**
         * 获得datatable的分页的数据格式
         * @returns {{sEcho: number, iTotalRecords: number, iTotalDisplayRecords: number, aaData: *[]}}
         */
        getDataTabelDtaObject : function(){
            var object = {
                "sEcho": 0,
                "iTotalRecords": 0,
                "iTotalDisplayRecords": 0,
                "iDisplayStart": 1,
                "iDisplayLength": 10,
                "aaData": []
            };
            return object;
        },
        /**
         * 对HTML字符串做处理，防止脚本注入
         * @param str
         * @returns {string}
         */
        htmlEncode : function(str){
            var s = "";
            if (!str || str.length == 0) {
                return "";
            }
            s = str.replace(/&/g, "&gt;");
            s = s.replace(/</g, "&lt;");
            s = s.replace(/>/g, "&gt;");
            s = s.replace(/ /g, "&nbsp;");
            s = s.replace(/\'/g, "&#39;");
            s = s.replace(/\"/g, "&quot;");
            s = s.replace(/\n/g, "<br>");
            return s;
        },

        getServerTime: function(cb){
            var self = this;
            var serverTime = "";
            var xhr = window.XMLHttpRequest?
                (new window.XMLHttpRequest()):
                (new ActiveObject("Microsoft"));
            xhr.open("HEAD","/");
            xhr.send(null);
            xhr.onreadystatechange = function(){
                if(xhr.readyState===2){
                    serverTime = +new Date( xhr.getResponseHeader("Date") );
                    cb && cb(serverTime)
                }
            };
        },

        format : function (date,fmt) {
            var o = {
                "M+": date.getMonth() + 1, //月份
                "d+": date.getDate(), //日
                "h+": date.getHours(), //小时
                "m+": date.getMinutes(), //分
                "s+": date.getSeconds(), //秒
                "q+": Math.floor((date.getMonth() + 3) / 3), //季度
                "S": date.getMilliseconds() //毫秒
            };
            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        },
        /**
         * 格式化时间(格式：yyyy-MM-dd HH:mm:ss)
         * @param time
         * @param type
         * @returns {string}
         */
        formatDate : function(time,type){
            var theCurrentDay ="";
            if(time == null || time == "" || time == "null") return "";
            var year = time.getFullYear();//年
            var month = time.getMonth()+1;//月
            if(parseInt(month)<10){
                month = '0'+month;
            }
            var date = time.getDate();//日
            if(parseInt(date)<10){
                date = '0'+date;
            }
            if(type == "date"){
                theCurrentDay = year + "-" + month + "-" + date;
            }else if(type == "cndate"){
                theCurrentDay = year + "年" + month + "月" + date + "日";
            }else if(type=='yearmonth'){
                theCurrentDay = year + "-" + month;
            }else if(type=='year'){
                theCurrentDay = year;
            }else if(type=='dateid'){
                var hours = time.getHours();//时
                if(parseInt(hours)<10){
                    hours = '0'+hours;
                }
                var minutes = time.getMinutes();//分
                if(parseInt(minutes)<10){
                    minutes = '0'+minutes;
                }
                var seconds = time.getSeconds();//秒
                if(parseInt(seconds)<10){
                    seconds = '0'+seconds;
                }
                theCurrentDay = year + month + date;
            }else if(type=='timeid'){
                var hours = time.getHours();//时
                if(parseInt(hours)<10){
                    hours = '0'+hours;
                }
                var minutes = time.getMinutes();//分
                if(parseInt(minutes)<10){
                    minutes = '0'+minutes;
                }
                var seconds = time.getSeconds();//秒
                if(parseInt(seconds)<10){
                    seconds = '0'+seconds;
                }
                theCurrentDay = year + month + date +  hours + minutes + seconds;
            }else if('cndateminute'==type){
                var hours = time.getHours();//时
                if(parseInt(hours)<10){
                    hours = '0'+hours;
                }
                var minutes = time.getMinutes();//分
                if(parseInt(minutes)<10){
                    minutes = '0'+minutes;
                }
                theCurrentDay = year + "年" + month + "月" + date + "日 " + hours + ":" + minutes;
            }else{
                var hours = time.getHours();//时
                if(parseInt(hours)<10){
                    hours = '0'+hours;
                }
                var minutes = time.getMinutes();//分
                if(parseInt(minutes)<10){
                    minutes = '0'+minutes;
                }
                var seconds = time.getSeconds();//秒
                if(parseInt(seconds)<10){
                    seconds = '0'+seconds;
                }
                theCurrentDay = year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds;
            }
            return theCurrentDay;
        },
        /**
         * 清空FORM
         * @param formId
         */
        clearForm: function(formId){
            $($("#" + formId).serializeArray()).each(function(){
                if(!$("#" + formId).find("#" + this.name).is('select')){
                    $("#" + formId).find("#" + this.name ).val("");
                }
            });
        },
        /**
         * 加载中图层
         * @param _divObj
         */
        loadMask:function(_divObj){
            var overlay = $('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
            _divObj.append(overlay);
        },
        /**
         * 去除加载中图层
         */
        unLoadMask:function(){
            $(".overlay").remove();
        },
        pageConfig : {
            "sProcessing":   "处理中...",
            "sLengthMenu":   "_MENU_ 记录/页",
            "sZeroRecords":  "没有匹配的记录",
            "sInfo":         "显示第 _START_ 至 _END_ 项记录，共 _TOTAL_ 项",
            "sInfoEmpty":    "显示第 0 至 0 项记录，共 0 项",
            "sInfoFiltered": "(由 _MAX_ 项记录过滤)",
            "sInfoPostFix":  "",
            "sSearch":       "搜索:",
            "sUrl":          "",
            "oPaginate": {
                "sFirst":    "首页",
                "sPrevious": "上页",
                "sNext":     "下页",
                "sLast":     "末页"
            }
        }
    };

    function getOuterUrl(url) {
        // 本地环境
        if(!!~location.host.indexOf('dev.')) {
            return 'http://daily.manage.51xianqu.com' + url;
        }
        // 线上环境
        else {
            return 'http://' + document.domain + url;
        }
    }

    $.extend({
        getUrlVars: function () {
            var vars = [], hash;
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
            return vars;
        },
        getUrlVar: function (name) {
            return $.getUrlVars()[name];
        }
    });

    CRM.dialog = window.dialog;
    window.CRM = CRM;
    window.juicer = juicer;

    return CRM;
});